<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        <label for="inputa">没有节流的input</label>
        <input type="text" id="inputa">
    </div>
    <div>
        <label for="inputb">防抖后的input</label>
        <input type="text" id="inputb">
    </div>
    <div>
        <label for="inputc">节流后的input</label>
        <input type="text" id="inputc">
    </div>
    <script>
        /*
            防抖:
                在事件被触发n秒后再执行回调，如果在这n秒内又被触发，则重新计时
            
        */ 
        function ajax(content){
            console.log("ajax request " + content)
        }
        let inputa = document.getElementById("inputa")

        inputa.addEventListener("keyup", function(e){
            ajax(e.target.value)
        })

        // 节流后的input
        function debounce(ms){
            let time = ms
            let timer = null
            return function (){
                let that = this
                clearTimeout(timer)
                timer = setTimeout(function(){
                    ajax(that.value)
                }, time)
            }
        }
        let inputb = document.getElementById("inputb")
        inputb.addEventListener("keyup", debounce(500))
        
        /*
            函数节流：
                规定在一个单位时间内，只能触发一次函数，如果这个单位时间内
                触发多次函数，只有一次生效
        */ 
        function throttle(ms){
            let time = ms
            let timer = null
            return function (){
                let that = this
                if (!timer){
                    timer = setTimeout(function(){
                        timer = null
                    }, ms)
                    ajax(that.value)
                }
            }
        }
        let inputc = document.getElementById("inputc")
        inputc.addEventListener("keyup", throttle(1000))




        // 数组分块
        function chunk(array, process, context){
            setTimeout(function(){
                var item = array.shift();
                process.call(context, item);
                
                if(array.length > 0){
                    setTimeout(argument.callee, 100)
                }
            }, 100)
        }

        // 函数节流
        function throttle(method, context){
            clearTimeout(method.tId);
            method.tId = setTimeout(function(){
                method.call(context)
            }, 100)
        }

        window.onresize = function(){
            throttle(resizeDiv)
        }
        function resizeDiv(){
            var div = document.getElementById("myDiv");
            div.style.height = div.offsetWidth + 'px'
        }
    </script>
</body>
</html>